import React, { useState, useEffect } from 'react';
import styled from '@emotion/styled';
import { useTranslation } from 'react-i18next';
import { useTTSBoardCast } from '@/views/Context/TTSBoardCastContext';
import Message from '@/utils/message';
import Loading from '@/components/Loading';
import { useStream, IStream } from '@/views/Context/StreamContext';
import AgentService from '@/modules/Agent';

interface SpeakingTipsProps {
	content?: string;
}

const SpeakingTipsWrapper = styled.div`
	height: 200px;
	min-height: 200px;
	width: 100%;
	overflow-y: auto;
	box-shadow: 0px 2px 6px 0px rgb(0 0 0 / 12%);
	border-radius: 2px;
	background: #ffffff;
	margin-bottom: 16px;
	padding: 0 14px;
	position: relative;
	overflow: hidden;

	.title {
		padding: 12px 0;
		font-size: 13px;
		font-weight: 500;
		color: #2d2d2d;
		margin: 0;
	}

	.content {
		font-size: 12px;
		color: #2d2d2d;
		line-height: 1.5;
	}
`;

const Title = styled.div`
	width: 100%;
	display: flex;
	align-items: center;
	justify-content: space-between;
`;

const IconSvg = styled.span`
	display: flex;
	padding: 0 4px;
	vertical-align: middle;
    width: 36px;
    height: 30px;
`;

const ContentWrapper = styled.div`
	overflow-y: auto;
	height: calc(100% - 44px);
`;

const SpeakingTips = (props: SpeakingTipsProps) => {
	const { t } = useTranslation();
	const { content = '' } = props;
	const { BoardCastModal, setBoardCastModal, TTSBoardCastStats, TTSBoardCastText, Speaking, setTTSBoardCastStats, stopSpeak, cancelTTSWithRecordMessage, startTTSPassAgeway, setTTSBoardCastText } =
		useTTSBoardCast();
	const [starting, setStarting] = useState(false);
	const [stoping, setStoping] = useState(false);
	// agent streams role: "agent"
	const [agentStreams, setAgentStreams] = useState<IStream[]>([]);
	const { smallStream } = useStream();

	useEffect(() => {
        console.log('TTSBoardCastStats()', TTSBoardCastStats());
		if (TTSBoardCastStats() === 'stow') {
            setTimeout(() => {
                setStarting(false);
            }, 1000);
		} else {
			setStoping(false);
		}
	}, [TTSBoardCastStats()]);

	useEffect(() => {
		const streams = smallStream().filter((stream: any) => stream.role === 'agent' && !stream.isRobot);
		// console.log('agentStreams', streams);
		setAgentStreams(streams);
	}, [smallStream()]);

	const startTTS = async () => {
		if (starting) return;
		if (!content?.trim()) {
			Message.warning('播报话术为空');
			return;
		}
		setStarting(true);
		setTTSBoardCastText(content);
        try {
            await startTTSPassAgeway();
        } catch (error) {
            console.error('startTTS', error);
            setStoping(false);
            setStarting(false);
        }
	};

	const stopTTS = async () => {
		if (stoping) return;
		setStoping(true);
		// setBoardCastModal(false);
		// setTTSBoardCastStats('default');
        try {
            await stopSpeak();
            await cancelTTSWithRecordMessage(TTSBoardCastText());
            Message.normal(t('tts-broadcast-cancelled'));
        } catch (error) {
            console.error('stopTTS', error);
            
            setStoping(false);
            setStarting(false);
        }
	};

	const BrocastButton = Speaking() ? (
		<IconSvg className="widget-icon" aria-hidden="true" onClick={stopTTS}>
			<svg className="widget-icon">
				<use xlinkHref={'#icon-widget-tingzhibobao'}></use>
			</svg>
		</IconSvg>
	) : (
		<IconSvg className="widget-icon" aria-hidden="true" onClick={startTTS}>
			<svg className="widget-icon">
				<use xlinkHref={'#icon-widget-bobao'}></use>
			</svg>
		</IconSvg>
	);

	return (
		<SpeakingTipsWrapper>
			<Title>
				<p className="title">话术提示</p>
				{Speaking() ? t('tts-broadcasting') : starting ? t('tts--broadcast-loading') : ''}
				{agentStreams[0]?.clientId === AgentService.user?.clientId && BrocastButton}
			</Title>
			<ContentWrapper>
				<p className="content">{content}</p>
			</ContentWrapper>
		</SpeakingTipsWrapper>
	);
};

export default SpeakingTips;
